import { addDialog } from "@/components/ReDialog";
import { hasAuth } from "@/router/utils";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import dayjs from "dayjs";
import { h, onMounted, reactive, ref } from "vue";
import editForm from "../form/index.vue";

// api
import { getStoreSimplePage } from "@/api/basicArchives/storeManagement"; // 门店
import { getSupplierSimplePage } from "@/api/basicArchives/supplierManagement"; // 获取供应商名称
import { getDepositorySimplePage } from "@/api/basicArchives/warehouseManagement"; // 仓库
import { getScrapPage, scrapAdd, scrapDel } from "@/api/stock/scrap";
import { dealDataExcept } from "@/utils/common";
import { goodsCodeRend, goodsNameRend } from "@/utils/tableColumns";

export function useExrule() {
  const form = reactive({
    scrapType: 1,
    documentNumber: "",
    depositoryName: "",
    processNumber: "",
    businessDate: [],
    businessDateStart: "",
    businessDateEnd: "",
    pageNum: 1,
    pageSize: 20
  });

  const selectData = ref({
    storeList: [],
    supplierList: [],
    ckList: []
  });

  const loading = ref(false);
  const dataList = ref([]);
  const fileList = ref();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true,
    pageSizes: [20, 50, 100]
  });

  const columns: TableColumnList = [
    {
      fixed: "left",
      type: "expand",
      slot: "expand"
    },
    {
      label: "业务日期",
      prop: "gmtCreate",
      minWidth: "120px",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD")
    },
    {
      label: "单据编号",
      prop: "documentNumber",
      minWidth: "120px"
    },
    {
      label: "申请流程编号",
      prop: "processNumber",
      minWidth: "120px"
    },
    {
      label: "仓库名称",
      prop: "depositoryName",
      minWidth: "120px"
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: "120px"
    },
    {
      label: "操作",
      prop: "putInPrice",
      minWidth: "100px",
      fixed: "right",
      slot: "operation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "specName",
      minWidth: 150,
      align: "left",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "specCode",
      align: "left",
      minWidth: 150,
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品条码",
      prop: "barCode",
      minWidth: 120,
      formatter: ({ barCode }) => barCode || "--"
    },
    {
      label: "库存均价",
      prop: "buyPrice",
      minWidth: 120,
      formatter: ({ avgBuyPrice }) => dealDataExcept(avgBuyPrice) || "--"
    },
    {
      label: "报废数量",
      prop: "scrapNum",
      minWidth: 120
    },
    {
      label: "报废总额",
      prop: "totalScrap",
      minWidth: 120,
      formatter: ({ totalScrap }) => dealDataExcept(totalScrap) || "--"
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function handleDelete(row) {
    const res = await scrapDel({ id: row.id });
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    // 处理请求参数
    let tempForm = { ...form };
    if (tempForm.businessDate && tempForm.businessDate.length > 0) {
      tempForm.businessDateStart = tempForm.businessDate[0];
      tempForm.businessDateEnd = tempForm.businessDate[1];
    }
    delete tempForm.businessDate;

    const { data } = await getScrapPage(tempForm);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.pageNum = val;
    onSearch();
  }

  const formRef = ref();
  const openDialog = () => {
    addDialog({
      sureBtnLoading: true,
      title: "新增报废单",
      props: {
        selectData: selectData.value
      },
      width: "1150px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: async (done, { closeLoading }) => {
        function chores() {
          message("新增成功", {
            type: "success"
          });
          done(); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }

        let obj = await formRef.value.getForm();
        if (obj.isPass) {
          scrapAdd(obj.params)
            .then(() => chores())
            .catch(() => closeLoading());
        } else {
          closeLoading();
        }
      }
    });
  };

  async function getCommon() {
    const params = {
      status: 0,
      pageNum: 1,
      pageSize: 999
    };
    // 供应商列表
    getSupplierSimplePage(params).then(res => {
      selectData.value.supplierList = res.data?.records || [];
    });

    // 门店
    getStoreSimplePage(params).then(res => {
      selectData.value.storeList = res.data?.records || [];
    });

    // 获取仓库列表 type 仓库类型 0门店仓 1供应链总仓 2区域仓
    getDepositorySimplePage(params).then(res => {
      selectData.value.ckList = res.data?.records || [];
    });
  }

  onMounted(() => {
    onSearch();

    getCommon();
  });

  return {
    form,
    columns,
    childColumns,
    loading,
    dataList,
    pagination,
    fileList,
    selectData,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    resetForm,
    openDialog,
    hasAuth,
    handleDelete
  };
}
